package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.PersonLiableAdapter;
import com.hengxinguotong.zhihuichengjian.bean.AddGroupPersonnelListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 提供给质量检查、安全检查、任务派发等功能中选择责任人
 * 提供给预约塔吊、预约升降机等功能中选择处理人
 * Created by Administrator on 2017/3/11.
 */

public class PersonLiableListActivity extends BaseActivity {
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_p)
    ImageView ivP;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    @BindView(R.id.personnel_lv)
    PullToRefreshListView personnelLv;
    private static final int MSG_UPDATE_INFO = 0x110;
    private int pageIndex = 1;
    private PersonLiableAdapter personAdapter;
    private List<User> mUsers;
    private User selectUser;
    private int type = 0;//0 责任人 ； 1 处理人
    private String unableUserId;//无法选择人员的id

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_INFO:
                    if (personnelLv != null) {
                        pageIndex = 1;
                        getPersonnelList(null);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_personnel);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        unableUserId = getIntent().getStringExtra("unableUserId");
        addListener();
        getPersonnelList(getResources().getString(R.string.loading));
    }


    private void addListener() {
        etProject.addTextChangedListener(searchTextWatcher);
        personnelLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectUser = (User) personAdapter.getItem(position - 1);
                personAdapter.notifyDataSetChanged();

            }
        });

        personnelLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getPersonnelList(null);
            }
        });
    }

    private void getPersonnelList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("name", etProject.getEditableText().toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = null;
        if(type == 0){
            url = "/person/queryPersonList/";
        }else{
            url = "/person/queryBuildingPersonList/";
        }
        Utils.requestData(alert, this, url + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AddGroupPersonnelListRes personnelListRes = gson.fromJson(json, AddGroupPersonnelListRes.class);
                    if(unableUserId != null){
                        unableUserFilter(personnelListRes);
                    }
                    addData(personnelListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
            }
        });
    }

    /**
     * 过滤无法选择人员
     *
     * @param personnelListRes
     */
    private int maxONCECOUNT = 10;//设置首次加载最大数量，初始化为10，过滤一个用户就减少1，以免无法触发上拉加载更多功能
    private void unableUserFilter(AddGroupPersonnelListRes personnelListRes) {
        List<User> allUsers = personnelListRes.getValue();
        Iterator<User> userIterator = allUsers.iterator();
        while (userIterator.hasNext()) {
            User user = userIterator.next();
            if(user.getUserId().equals(unableUserId)){//过滤已选择受伤人员
                userIterator.remove();
                maxONCECOUNT--;
            }
        }
    }

    private void addData(List<User> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(personnelLv);
            }else{
                dismissEmptyView();
            }
            mUsers = datas;
            personAdapter = new PersonLiableAdapter(mUsers, this);
            personnelLv.setAdapter(personAdapter);
            if (datas.size() == maxONCECOUNT) {
                personnelLv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            }
        } else {
            mUsers.addAll(datas);
            personAdapter.notifyDataSetChanged();
        }

        if (datas.size() < maxONCECOUNT) {
            personnelLv.setMode(PullToRefreshBase.Mode.DISABLED);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @OnClick({R.id.iv_back, R.id.save_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                Intent intent = getIntent();
                if (selectUser != null) {
                    intent.putExtra("selectUser", selectUser);
                    setResult(1, intent);
                    finish();
                }else{
                    showToast("请选择人员");
                }
                break;
        }
    }


    private TextWatcher searchTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 500);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    public User getSelectUser() {
        return selectUser;
    }
}
